var fs = require("fs");
var piexif = require("./piexif.js");
var http = require('http');
//require("//api.map.baidu.com/api?v=3.0&ak=BA7a941611feddd5977215b8b08afbb8")

function Get(src, cb)
{
	http.get(src, function(res){
		let err;
		const { statusCode } = res;
		let rawData = "";

		if (!statusCode === 200) 
			err = new Error("服务器响应失败");
		if (!/application\/json/.test(res.headers["content-type"]))
			 err = new Error("数据格式错误，需要json格式");
		if (err) {
			console.log(err);
			//释放内存
			res.resume();
			return;
		}

		// chunk是16进制BUFFER数据，需要转成字符打印
		res.on("data", (chunk) => {
			rawData += chunk;
		});

		//监听请求结束
		res.on("end", () => {
			try {
				//console.log(rawData);
				cb(rawData);
			} catch (e) {
				console.log(e);
			}
		});
	});
}

function DoOne()
{
	if (!data[i].endsWith("road") && !data[i].endsWith("ROAD"))
	{
		i++;
		if (i < data.length)
			DoOne();
		return;
	}
	console.log(data[i]);
	
	filecon = fs.readFileSync("image\\" + data[i], 'utf-8');
	//console.log(filecon);
	
	rrr = JSON.parse(filecon);
	console.log(rrr);
	 p = rrr.subpaths[0].points[0];
	console.log(p);
	i1 = 0;i2=0;
	Get("http://api.map.baidu.com/geoconv/v1/?coords=" + p.lng + "," + p.lat + "&from=5&to=3&ak=BA7a941611feddd5977215b8b08afbb8", callback);
}

function callback(data){
	data = JSON.parse(data);//console.log(data);
	var r = data.result[0];
	var x = r.x;
	var y = r.y;
	
	//console.log(i1,i2,x, y);
	
	deltaX = x - p.lng;
	deltaY = y - p.lat;
	
	count = 0;
	
	//if (i1 < rrr.subpaths.length)
	{
		var sp = rrr.subpaths[i1];
		//sp.type = Number(sp.type);

		while (i2 < sp.points.length)
		{
			if (count > 20)
			{
				count = 0;
				p = rrr.subpaths[i1].points[i2];
				Get("http://api.map.baidu.com/geoconv/v1/?coords=" + p.lng + "," + p.lat + "&from=5&to=3&ak=BA7a941611feddd5977215b8b08afbb8", callback);
				return;
			}
			
			var oldP = sp.points[i2];
			var newP = new Array();
			newP[0] = Number((oldP.lng + deltaX).toFixed(6));
			newP[1] = Number((oldP.lat + deltaY).toFixed(6));
			
			sp.points[i2] = newP;
			
			count++;
			
			i2++;
		}
		i1++;		i2 = 0;
		if(i1 < rrr.subpaths.length)
		{
			np = rrr.subpaths[i1].points[0];
			if(np!=null)
				p=np;
		Get("http://api.map.baidu.com/geoconv/v1/?coords=" + p.lng + "," + p.lat + "&from=5&to=3&ak=BA7a941611feddd5977215b8b08afbb8", callback);
	}
		else	
			DoOne2();
	}
};	

function DoOne2()
{	
	fs.writeFileSync("out\\" + data[i], JSON.stringify(rrr), 'utf-8');
	
	i++;
	if (i < data.length)
		DoOne();
}

fs.readdir("image", function (err, dat){
	if (err)
	{
		console.log(err);
	}
	else
	{
		data = dat;
		i = 0;
		DoOne();
	}
});